package com.superbytecode.common.context;

import com.superbytecode.common.model.LoginInformation;

import java.util.Optional;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: superbytecode-beacon
 * @Package: com.superbytecode.framework.common.context
 * @ClassName: UserContext
 * @Description: [用户上下文信息]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2023/11/22 9:40
 * @Version: V1.0
 * @Copyright: 2023 www.super-bytecode.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
public class UserContext {
    private static final ThreadLocal<LoginInformation> USER_THREAD_LOCAL = new ThreadLocal<>();

    //
    public static void set(LoginInformation information) {
        USER_THREAD_LOCAL.set(information);
    }

    public static LoginInformation get() {
        return USER_THREAD_LOCAL.get();
    }

    public static void remove() {
        USER_THREAD_LOCAL.remove();
    }

    public static boolean loginActive() {
        return Optional.ofNullable(USER_THREAD_LOCAL.get()).isPresent();
    }

    public static Long getUserId() {
        return USER_THREAD_LOCAL.get().getUserId();
    }

    public static Long getUserIdOrDefault() {
        Optional<LoginInformation> optional = Optional.ofNullable(USER_THREAD_LOCAL.get());
        return optional.isPresent() ? optional.get().getUserId() : 0L;
    }

    public static Long getUserIdOrNull() {
        Optional<LoginInformation> optional = Optional.ofNullable(USER_THREAD_LOCAL.get());
        return optional.map(LoginInformation::getUserId).orElse(null);
    }
}